//
//  LostPropertyViewController.m
//  HuLaQuan
//
//  Created by liyan on 16/1/19.
//  Copyright © 2016年 yuwubao. All rights reserved.
//

#import "LostPropertyViewController.h"
#import "YuLoginInputInfoField.h"
#import "AQPhotoPickerView.h"

#import "UserTypeInfoCell.h"
#import "LostPropertyTableViewCell.h"
#import "LostPropertyImageCell.h"
#import "ConfirmButtonCell.h"

#import "YuUserCellLabel.h"

//logic model
#import "LAFEngine.h"

#import "PhotoController.h"

@interface LostPropertyViewController ()<UITextFieldDelegate,UIGestureRecognizerDelegate,UITextViewDelegate,UIActionSheetDelegate,AQPhotoPickerViewDelegate>

@property (strong, nonatomic) NSArray *LostProperty;
@property(strong,nonatomic)UITapGestureRecognizer *tap;

@property(strong,nonatomic)UIImage *image;

@property (strong,nonatomic) NSMutableArray *imageArray;
@property (strong,nonatomic) NSMutableArray *imageURLArray;
//getInformation
@property(copy,nonatomic)NSString *lostName;
@property(copy,nonatomic)NSString *name;
@property(copy,nonatomic)NSString *phone;
@property(copy,nonatomic)NSString *time;
@property(copy,nonatomic)NSString *content;


//logic model
@property(nonatomic,strong)LAFEngine *lostAndFoundEngine;


@end

@implementation LostPropertyViewController

static NSString * const LostPropertyFiled = @"UserTypeInfoCell";
static NSString * const LostPropertyViewed = @"LostPropertyTableViewCell";
static NSString * const LostPropertyImage = @"LostPropertyImageCell";
static NSString * const LostPropertyConfirm = @"ConfirmButtonCell";

- (NSMutableArray *)imageURLArray
{
    if (!_imageURLArray) {
        _imageURLArray = [[NSMutableArray alloc] init];
    }
    return _imageURLArray;
}
- (NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [[NSMutableArray alloc] init];
    }
    return _imageArray;
}
-(LAFEngine *)lostAndFoundEngine
{
    if (!_lostAndFoundEngine) {
        _lostAndFoundEngine = [[LAFEngine alloc]init];
    }
    return _lostAndFoundEngine;
}

- (NSArray *)LostProperty
{
    if (!_LostProperty) {
        _LostProperty = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"LostProperty" ofType:@"plist"]];
    }
    return _LostProperty;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setupUI
{
    [self setupFooterForTableView];
    [self setupNavBackButton];
    self.title = @"失物招领";
    
    
    [self.tableView registerNib:[UserTypeInfoCell nib] forCellReuseIdentifier:LostPropertyFiled];
     [self.tableView registerNib:[LostPropertyTableViewCell nib] forCellReuseIdentifier:LostPropertyViewed];
     [self.tableView registerNib:[LostPropertyImageCell nib] forCellReuseIdentifier:LostPropertyImage];
     [self.tableView registerNib:[ConfirmButtonCell nib] forCellReuseIdentifier:LostPropertyConfirm];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
}

// 加手势处理键盘
- (void)setupTapGesture
{
    _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handelGenericTapView:)];
    _tap.delegate = self;
    [self.view addGestureRecognizer:_tap];
}
- (void)handelGenericTapView:(UITapGestureRecognizer *)sender
{
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        // handling code
        //[self.view endEditing:YES];
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
    }
}
#pragma mark - Textfield delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    textField.placeholder = nil;
    // 加手势处理键盘
    [self setupTapGesture];
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.text.length == 0 ) {
        YuLoginInputInfoField *textF = (YuLoginInputInfoField *)textField;
        
        textF.placeholder = self.LostProperty[textField.tag][@"placeholder"];
    }
    [self.view removeGestureRecognizer:_tap];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
#pragma mark - TextView delagate
-(void)textViewDidChange:(UITextView *)textView
{
    _content = textView.text;
}
#pragma mark UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (0 == section) {
        return 4;
    }
    else
    {
        return 1;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ( 0 == indexPath.section) {
        UserTypeInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:LostPropertyFiled
                                                            forIndexPath:indexPath];
        cell.textField.placeholder = self.LostProperty[indexPath.row][@"placeholder"];
        [cell.textField addTarget:self action:@selector(detaileAddressFieldWithText:) forControlEvents:UIControlEventEditingChanged];
        
        cell.textField.delegate = self;
        cell.textField.tag = indexPath.row;
        return cell;
        
    }
    
    else if (1 == indexPath.section)
    {
        LostPropertyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LostPropertyViewed forIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
        cell.contentString.delegate = self;
        return cell;
    }
    else if (2 == indexPath.section)
    {
        LostPropertyImageCell *cell = [tableView dequeueReusableCellWithIdentifier:LostPropertyImage forIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
        cell.tag = 100;
        [cell.lostChoose addTarget:self action:@selector(choosePhoto) forControlEvents:UIControlEventTouchUpInside];
        if (!_image) {
            cell.lostImage.image = [UIImage imageNamed:@"images"];
        }
        else
        {
            cell.lostImage.image = _image;
        }
        
        return cell;
    }
    else
    {
        ConfirmButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:LostPropertyConfirm forIndexPath:indexPath];
        [cell.confirmButton setTitle:@"确定" forState:UIControlStateNormal];
        cell.confirm = (ClickBlock)^(){
            [self confirmButton];
        };
        return cell;
    }
    
}
//getInformation
- (void)detaileAddressFieldWithText:(UITextField *)textField
{
    switch (textField.tag) {
        case 0:
            self.lostName = textField.text;
            break;
        case 1:
            self.name = textField.text;
            break;
        case 2:
            self.phone = textField.text;
            break;
        default:
            self.time = textField.text;
            break;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.section) {
        return kNormalCellHeight;
    }
    else if (1 == indexPath.section)
    {
        return 100;
    }
    else if(2 == indexPath.section)
    {
        return 100;
    }
    else
    {
        return kConfirmButtonCellHeight;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section != 1) {
        return kUserCenterSectionHeaderHeight;
    }
    else
    {
        return 50;
    }
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

{
    if (section == 1) {
        CGRect frameRect = CGRectMake(25, 0, 200, 40);
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
        YuUserCellLabel *textSection = [[YuUserCellLabel alloc] initWithFrame:frameRect];
        textSection.text = @"相关描述";
        [view addSubview:textSection];
        return view;
    }
    
    return nil;
    
}

#pragma mark - Button Events
//touch
-(void)confirmButton
{
    NSLog(@"lostName:%@ phone:%@ time:%@ content:%@ image:%@",self.lostName,self.phone,self.time,self.content,self.image);
    // [self.lostAndFoundEngine lostandFound:self.lostName andOwnerPhone:self.phone andOwnerLoatTime:self.time andOwnerDesc:self.content andOwnerPic:@""];
    
    if (self.lostName.length && self.phone.length && self.time.length && self.content.length &&self.image) {
        
        [self.lostAndFoundEngine lostandFound:self.lostName andOwnerPhone:self.phone andOwnerLoatTime:self.time andOwnerDesc:self.content andOwnerPic:[self.imageURLArray copy]];
        
        
    }else{
        [self.view makeToast:@"您还未将信息填写完全"];
        
        
    }
    //
    
    
}
-(void)choosePhoto
{
    PhotoController *photo = [[PhotoController alloc]init];
    photo.view.frame = CGRectMake(0, self.view.frame.size.height-150,self.view.frame.size.width ,150 );
    [self addChildViewController:photo];
    [self.view addSubview:photo.view];
    photo.delegateViewController = self;
    
    //[AQPhotoPickerView presentInViewController:self];
}

#pragma mark - Call Back

- (void)lostandFoundFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"您登记的失物招领信息已提交到952，一有与您丢失物品相关信息，我们将及时通知给您" andBlock:^(UIAlertAction *action ) {
            if ([action.title isEqualToString:@"好的"]) {
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        }  type:@"confirm"];
        [self presentViewController:x animated:YES completion:nil];
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}
- (void)imageUploadFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        NSLog(@"%@",messageDic[@"result"]);
        
        [self.imageURLArray setObject:messageDic[@"result"][@"imgURL"] atIndexedSubscript:0];
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
    
}

#pragma mark - Life Cycle

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(lostandFoundFinish:) name:@"LostandFoundFinish" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(imageUploadFinish:) name:@"LostImageUploadFinish" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"LostandFoundFinish" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"LostImageUploadFinish" object:nil];
    
}
#pragma mark - UIActionSheetDelegate

#pragma mark - AQPhotoPickerViewDelegate methods
-(void)photoFromImagePickerView:(UIImage*) photo {
    
    _image = photo;
    
    [self.imageArray setObject:photo atIndexedSubscript:0];
    
    [self.tableView reloadData];
    
    [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    [self.lostAndFoundEngine imageUpload:[self.imageArray copy]];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
